package com.c3po.utils;

import java.util.List;
import java.util.Map;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;


/**
 * redis cache 工具类
 * 
 */
public class RedisUtil {
	public final static String VIRTUAL_COURSE_PREX = "_lc_vc_";

	/**
	 * 非切片链接池
	 */
	private JedisPool jedisPool;

	private String ip="127.0.0.1";

	/**
	 * 初始化Redis连接池
	 */
/*	static {
		try {
			// 加载redis配置文件
			ResourceBundle bundle = ResourceBundle.getBundle("redis");
			if (bundle == null) {
				throw new IllegalArgumentException(
						"[redis.properties] is not found!");
			}
			int maxActivity = Integer.valueOf(bundle
					.getString("redis.pool.maxActive"));
			int maxIdle = Integer.valueOf(bundle
					.getString("redis.pool.maxIdle"));
			long maxWait = Long.valueOf(bundle.getString("redis.pool.maxWait"));
			boolean testOnBorrow = Boolean.valueOf(bundle
					.getString("redis.pool.testOnBorrow"));
//			boolean onreturn = Boolean.valueOf(bundle
//					.getString("redis.pool.testOnReturn"));
			
//			ip = bundle.getString("redis.ip");
//			port = bundle.getString("redis.port");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
*/
	/**
	 * 构造函数
	 */
	public RedisUtil() {
	}

	/**
	 * 非切片连接池初始化
	 */
	private void initialPool() {
		// 池基本配置
		 //控制一个pool可分配多少个jedis实例，通过pool.getResource()来获取；
		JedisPoolConfig config = new JedisPoolConfig();
		config.setMaxTotal(100);//最大连接数
		config.setMaxIdle(5);//最大空闲连接数
		config.setMaxWaitMillis(1000);//获取连接时的最大等待毫秒数
		config.setTestOnBorrow(true);//在borrow一个jedis实例时，是否提前进行validate操作；如果为true，则得到的jedis实例均是可用的；
		jedisPool = new JedisPool(config, ip, 6379);
	}


	/**
	 * 在多线程环境同步初始化
	 */
	private synchronized void poolInit() {
		if (jedisPool == null) {
			initialPool();
		}
	}

	/**
	 * 非切片客户端链接 同步获取非切片Jedis实例
	 * 
	 * @return Jedis
	 */
	public synchronized Jedis getJedis() {
		if (jedisPool == null) {
			poolInit();
		}
		Jedis jedis = null;
		try {
			if (jedisPool != null) {
				jedis = jedisPool.getResource();
				// jedis.auth(redisCacheConfig.getAuth());
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			returnResource(jedis);
		}
		return jedis;
	}

	

	/**
	 * 释放jedis资源
	 * 
	 * @param jedis
	 */
	@SuppressWarnings("deprecation")
	public void returnResource(final Jedis jedis) {
		if (jedis != null && jedisPool != null) {
			jedisPool.returnResource(jedis);
		}
	}

	/**
	 * 得到Key
	 * 
	 * @param key
	 * @return
	 */
	public String buildKey(String key) {
		return VIRTUAL_COURSE_PREX + key;
	}

	/**
	 * 设置 String
	 * 
	 * @param key
	 * @param value
	 */
//	 public void setString(String key ,String value){
//	 try {
//	 value = StringUtil.isNullOrEmpty(value) ? "" : value;
//	 getJedis().set(buildKey(key),value);
//	 } catch (Exception e) {
//	
//	 }
//	 }

	/**
	 * 设置 过期时间
	 * 
	 * @param key
	 * @param seconds
	 *            以秒为单位
	 * @param value
	 */
	// public void setString(String key ,int seconds,String value){
	// try {
	// value = StringUtil.isNullOrEmpty(value) ? "" : value;
	// getJedis().setex(buildKey(key), seconds, value);
	// } catch (Exception e) {
	//
	// }
	// }

	public boolean exist(String key) {
		String bKey = buildKey(key);
		if (getJedis() == null || !getJedis().exists(bKey)) {
			return false;
		}
		return true;
	}

	/**
	 * 向缓存中设置对象
	 * 
	 * @param key
	 * @param bean
	 */
	public void setString(String key, String param) {
		String bKey = buildKey(key);
		try {
			getJedis().set(bKey.getBytes(), SerializeUtil.serialize(param));
		} catch (Exception e) {

		}
	}

	/**
	 * 获取String值
	 * 
	 * @param key
	 * @return value
	 */
	public String getString(String key) {
		String bKey = buildKey(key);
		if (getJedis() == null || !getJedis().exists(bKey)) {
			return null;
		}
		byte[] in = getJedis().get(bKey.getBytes());
		String str = (String)SerializeUtil.unserialize(in);
		return str;
	}

	/**
	 * 向缓存中设置对象
	 * 
	 * @param key
	 * @param bean
	 */
	public <T> void setBean(String key, Object bean) {
		String bKey = buildKey(key);
		try {
			 System.out.println(bean);
			getJedis().set(bKey.getBytes(), SerializeUtil.serialize(bean));
		} catch (Exception e) {
             System.out.println(e);
		}
	}

	/**
	 * 根据key 获取对象
	 * 
	 * @param key
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public <T> T getBean(String key) {
		String bKey = buildKey(key);
		if (getJedis() == null || !getJedis().exists(bKey.getBytes())) {
			return null;
		}
		byte[] in = getJedis().get(bKey.getBytes());
		T bean = (T) SerializeUtil.unserialize(in);
		return bean;

	}

	/**
	 * 设置 list
	 * 
	 * @param <T>
	 * @param key
	 * @param value
	 */
	public <T> void setList(String key, List<T> list) {
		String bKey = buildKey(key);
		try {
			getJedis().set(bKey.getBytes(), SerializeUtil.serialize(list));
		} catch (Exception e) {
			  System.out.println(e);
		}
	}

	/**
	 * 获取list
	 * 
	 * @param <T>
	 * @param key
	 * @return list
	 */
	@SuppressWarnings("unchecked")
	public <T> List<T> getList(String key) {
		String bKey = buildKey(key);
		if (getJedis() == null || !getJedis().exists(bKey.getBytes())) {
			return null;
		}
		byte[] in = getJedis().get(bKey.getBytes());
		List<T> list = (List<T>) SerializeUtil.unserialize(in);
		return list;
	}

	/**
	 * 设置 map
	 * 
	 * @param <T>
	 * @param key
	 * @param value
	 */
	public <T> void setMap(String key, Map<String, T> map) {
		String bKey = buildKey(key);
		try {
			getJedis().set(bKey.getBytes(), SerializeUtil.serialize(map));
		} catch (Exception e) {
			  System.out.println(e);
		}
	}

	/**
	 * 获取list
	 * 
	 * @param <T>
	 * @param key
	 * @return list
	 */
	@SuppressWarnings("unchecked")
	public <T> Map<String, T> getMap(String key) {
		String bKey = buildKey(key);
		if (getJedis() == null || !getJedis().exists(bKey.getBytes())) {
			return null;
		}
		byte[] in = getJedis().get(bKey.getBytes());
		Map<String, T> map = (Map<String, T>) SerializeUtil.unserialize(in);
		return map;
	}
	


}
